package com.dhl.demo.service.impl;

import com.dhl.demo.domain.RedisLock;
import com.dhl.demo.service.IRedisLockService;
import com.dhl.demo.mapper.RedisLockMapper;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 延迟双删
 * @author danghailiang
 * @date 2023年03月13日 10:42
 */
@Service
public class RedisLockServiceImpl implements IRedisLockService {

    @Resource
    private RedisLockMapper redisLockMapper;
    @Resource
    private RedisTemplate<String,List<RedisLock>> redisTemplate;
    @Override
    public void addSum() {
        int sum = redisLockMapper.select();
        redisLockMapper.update(++sum);
    }

    @Override
    public void insert() {
        // 删除缓存
        redisTemplate.delete("redisData");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 添加数据
        redisLockMapper.insert(1);
        // 延迟
        redisTemplate.delete("redisData");
        try {
            // 此处睡眠时间，应该大于一次查询时间
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 删除缓存
        redisTemplate.delete("redisData");
    }

    @Override
    public List<RedisLock> findAll(){
        List<RedisLock> redisData = redisTemplate.opsForValue().get("redisData");
        if(Objects.nonNull(redisData)){
            return redisData;
        }
        redisData = redisLockMapper.findAll();
        redisTemplate.opsForValue().set("redisData",redisData,100,TimeUnit.SECONDS);
        return redisData;
    }
}
